from wormbane.action import do_hit_monster, do_move, ActionError
from wormbane.command import handle_command
from wormbane.CursesUi import CursesUi
from wormbane.Game import Game
from wormbane.geometry import chebyshev_distance
from wormbane.save import load_game, remove_save_file, save_game
import curses, random, signal


def ignore_signal(signal, frame):
    pass


def main():
    signal.signal(signal.SIGINT, ignore_signal)
    print curses.wrapper(wrapped_main)


def wrapped_main(stdscr):

    curses.use_default_colors()
    for i in xrange(curses.COLOR_RED, curses.COLOR_WHITE + 1):
        curses.init_pair(i, i, -1)
    ui = CursesUi(stdscr)

    # Attempt to load a previously saved game.
    try:
        game = load_game()
    except IOError:
        game = Game()

    command = None
    while (not game.completed and game.hero.alive
           and command not in ('quit', 'save')):
        monster = game.current_level.pop_monster()
        if monster is game.hero:
            game.current_level.update_light_and_sight(game.hero)
            ui.update_screen(game)
            del game.messages[:]
            command = ui.read_command()
            if command not in ('quit', 'save'):
                handle_command(command, game)
        else:
            if (game.hero.pos is not None
                and chebyshev_distance(monster.pos, game.hero.pos) == 1):
                do_hit_monster(monster, game.hero, game)
            else:
                neighbors = list(monster.env.neighbors)
                if neighbors:
                    try:
                        do_move(monster, random.choice(neighbors), game)
                    except ActionError:
                        monster.time += 1.0 / monster.speed
                else:
                    monster.time += 1.0 / monster.speed
        game.current_level.push_monster(monster)
    if game.completed:
        try:
            remove_save_file()
        except OSError:
            pass
        return 'You won the game.'
    elif not game.hero.alive:
        try:
            remove_save_file()
        except OSError:
            pass
        return 'You die...'
    elif command == 'save':
        save_game(game)
        return 'Your game was saved.'
    else:
        try:
            remove_save_file()
        except OSError:
            pass
        return 'You quit the game.'


if __name__ == '__main__':
    main()
